import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Notification, Modal, Message } from '@arco-design/web-vue';
import qs from 'qs';
// import { useUserStore } from '@/store';
// import { RenderContent } from '@arco-design/web-vue/es/_utils/types';
import { getToken } from '@/utils/auth';
import { useUserStore } from '@/store/modules/user';

let errorDialogShow = false;

export interface HttpResponse<T = unknown> {
  message: string;
  code: number;
  data: T;
}

// 配置请求路径和超时时间
axios.defaults.baseURL = `${process.env.BASE_API}`;
axios.defaults.timeout = 30000;

// 请求拦截器
axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (config.headers && getToken()) {
      config.headers['X-System-Token'] = getToken() || '';
    }
    const params = qs.stringify(config.params)
    if (params !== "") {
      config.url += "?" + params
      config.params = undefined
    }
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    if (res.code === 200) {
      // Message.success({ content: res.message, id: res.message })
      return res.data;
    } else {
      if ((res.code === 10008 || res.code === 10005 || res.code === 10007 || res.code === 401) && !errorDialogShow) {
        errorDialogShow = true;
        Modal.warning({
          title: '认证消息',
          content: res.message,
          okText: '确定',
          maskClosable: false,
          async onOk() {
            errorDialogShow = false;
          },
        });
      }
      Message.error({ content: res.message, id: res.message });
      return Promise.reject(new Error(res.message || 'Error'));
    }
  },
  (error) => {
    // Message.error({
    //   content: '请求失败',
    //   duration: 5 * 1000,
    // });
    return Promise.reject(error);
  }
);
